package org.example.crop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.crop.domain.*;
import org.example.crop.service.SizeService;
import org.example.crop.service.StashCropService;
import org.example.crop.service.StashService;
import org.example.crop.mapper.StashMapper;
import org.example.crop.service.StashSizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
* @author scf
* @description 针对表【t_stash】的数据库操作Service实现
* @createDate 2024-05-24 16:35:08
*/
@Service
public class StashServiceImpl extends ServiceImpl<StashMapper, Stash>
    implements StashService{
    @Autowired
    private StashCropService stashCropService;
    @Autowired
    private StashSizeService stashSizeService;
    @Autowired
    private SizeService sizeService;
    @Override
    @Transactional
    public boolean saveAll(Crop crop) {
        StashCrop stashCrop = new StashCrop();
        stashCrop.setCropId(crop.getId());
        LambdaQueryWrapper<Stash> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Stash::getName,crop.getTname());
        Stash stash = this.getOne(wrapper);
//        stashCrop.setStashId(stash.getId());
        stashCrop.setNum(crop.getNum());
        stashCrop.setCreateDate(new Date());
        if(crop.getSize()>5){
            return false;
        }
        if(crop.getSize()<=3){
            Integer sizeId=sizeService.getSizeId();
            LambdaQueryWrapper<StashSize> StashSizewrapper = new LambdaQueryWrapper<>();
            StashSizewrapper.eq(StashSize::getStashId,stash.getId());
            StashSizewrapper.eq(StashSize::getSizeId,sizeId);
            StashSize stashSize = stashSizeService.getOne(StashSizewrapper);
            if(stashSize.getNum()-crop.getNum()<0){
                return false;
            }
            stashSize.setNum(stashSize.getNum()-crop.getNum());
            stashSizeService.updateById(stashSize);
            stashCrop.setStsId(stashSize.getId());
        }
        if(crop.getSize()>3&&crop.getSize()<=5){
            Integer sizeId=sizeService.getSizeId2();
            LambdaQueryWrapper<StashSize> StashSizewrapper = new LambdaQueryWrapper<>();
            StashSizewrapper.eq(StashSize::getStashId,stash.getId());
            StashSizewrapper.eq(StashSize::getSizeId,sizeId);
            StashSize stashSize = stashSizeService.getOne(StashSizewrapper);
            if(stashSize.getNum()-crop.getNum()<0){
                return false;
            }
            stashSize.setNum(stashSize.getNum()-crop.getNum());
            stashSizeService.updateById(stashSize);
            stashCrop.setStsId(stashSize.getId());
        }
        boolean save = stashCropService.save(stashCrop);
        return save;
    }
}




